package cn.list

/**
  * Created by lzd on 2018/11/8.
  */
object ListDemo1 {
  def main(args: Array[String]): Unit = {
    val lst0 = List(1, 7, 9, 8, 0, 3, 5, 4, 6, 2)

    //每个元素乘以10
    val lst1 = lst0.map(_ * 10)
    println(lst1)

    //取偶数生成新的集合
    val lst2 = lst0.filter(_ % 2 == 0)
    println(lst2)

    //排序
    println(lst0.sorted)
    println(lst0.sortBy(x => x))
    val lstsortby = Map(("hello", 2), ("ahello", 3), ("zhello", 1))
    println(lstsortby.toList.sortBy(_._1))
    println(lst0.sortWith((x, y) => x > y))

    //反转
    println(lst0.reverse)

    //分组/压扁/iterator转list
    println(lst0.grouped(3).toList)
    println(lst0.grouped(3).toList.flatten)
    val lstgroupby = Array(("hello", 2), ("hello", 3), ("hello", 1))
    println(lstgroupby.toList.groupBy(_._1))
    val lstgroupby1 = Map(("hello", 2), ("hello", 3), ("hello", 1))
    println(lstgroupby1)
    println(lstgroupby1.groupBy(_._1))


    //先按空格切分，再压扁
    val a = Array("a b c", "d e f", "h i j")
    val aa = a.flatMap(_.split(" "))
    println(aa.toBuffer)

    /** reduce fold(可以设置初始值) */
    println(lst0.reduce(_ + _))
    println(lst0.reduceLeft(_ + _))
    println(lst0.reduceRight(_ + _))

    println(lst0.fold(10)(_ + _))
    println(lst0.foldLeft(10)(_ + _))
    println(lst0.foldRight(10)(_ + _))

    /** aggregate 合计汇总 */
    val agglst = List(List(1, 2, 3), List(1, 2, 3), List(1, 2, 3), List(1, 2, 3))

    val sum = agglst.aggregate(100)(_ + _.sum, _ + _)
    println(sum)


    /**多个集合操作*/
    //list可以添加重复，不会去重
    val l1 = List(1,2,3,4)
    val l2 = List(3,4,5,6)
    //set 合并去重
    val s1 = Set(1,2,3,4)
    val s2 = Set(3,4,5,6)

    //union求并集
    println("求并集")
    println(l1 union l2)
    println(s1 union(s2))

    //求交集
    println(l1.intersect(l2))
    println(s1.intersect(s2))

    //求差集
    println(l1.diff(l2))
    println(l2.diff(l1))

    /**多线程并行计算par*/
    println(lst0.par.reduce(_+_))
    //初始值可能会多个线程分配，计算的结果值不确定
    println(lst0.par.fold(10)(_+_))
    println(agglst.par.aggregate(100)(_+_.sum,_+_))

  }
}
